/*
 * Copyright (c) 2010 Andy Aspell-Clark
 * 
 * Permission is hereby granted, free of charge, to any person
 * obtaining a copy of this software and associated documentation
 * files (the "Software"), to deal in the Software without
 * restriction, including without limitation the rights to use,
 * copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following
 * conditions:
 * 
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
 * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
 * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
 * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 * OTHER DEALINGS IN THE SOFTWARE.
 */
package uk.org.aspellclark.agenedb.view.individual;

import java.util.ArrayList;
import java.util.List;

import uk.org.aspellclark.agenedb.Preferences;
import uk.org.aspellclark.agenedb.R;
import uk.org.aspellclark.agenedb.view.GedcomTreeView;
import uk.org.aspellclark.common.ImageFunctions;
import uk.org.aspellclark.gedcom.controller.Db4oController;
import uk.org.aspellclark.gedcom.controller.IndividualController;
import uk.org.aspellclark.gedcom.model.records.IndividualRecord;
import uk.org.aspellclark.gedcom.model.structures.IndividualEventStructure;
import uk.org.aspellclark.gedcom.model.structures.MultimediaLink;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Gallery;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

public class IndividualDetailsView extends Activity implements OnClickListener {

	private static String LOG_TAG = "IndivDetsView";

	private IndividualController individualCntrlr;

	private static final int ID_DIALOG_PROGRESS = 16384;

	@Override
	public void onClick(View arg0) {
		Intent intnt = new Intent(this.getBaseContext(), GedcomTreeView.class);
		this.startActivity(intnt);
	}

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		//this.showDialog(ID_DIALOG_PROGRESS);

		this.setContentView(R.layout.individual_details_view);

		Button btnShowTree = (Button) this.findViewById(R.id.individualDetailsViewBtnShowTree);
		btnShowTree.setOnClickListener(this);

		this.individualCntrlr = new IndividualController(Db4oController.getInstance());

		this.updateIndividualDetails();

		//this.dismissDialog(ID_DIALOG_PROGRESS);
	}

	//	@Override
	//	protected Dialog onCreateDialog(int id) {
	//		if (id == ID_DIALOG_PROGRESS) {
	//			ProgressDialog loadingDialog;
	//			loadingDialog = new ProgressDialog(this);
	//			loadingDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
	//			loadingDialog.setIndeterminate(true);
	//			loadingDialog.setCancelable(false);
	//			loadingDialog.setProgress(0);
	//			return loadingDialog;
	//		}
	//
	//		return super.onCreateDialog(id);
	//	}

	private void updateIndividualDetails() {
		try {
			IndividualRecord indiv = this.individualCntrlr.getIndividual(Preferences.currentIndividualId);

			if (indiv != null) {
				TextView firstnameVw = (TextView) this.findViewById(R.id.txtFirstNames);
				firstnameVw.setText(indiv.getNameFirst());

				TextView lastnameVw = (TextView) this.findViewById(R.id.txtLastNames);
				lastnameVw.setText("/" + indiv.getNameLast() + "/");

				TextView dobVw = (TextView) this.findViewById(R.id.txtDateBirth);
				dobVw.setText("Born: " + indiv.getDOB());

				TextView dodVw = (TextView) this.findViewById(R.id.txtDateDeath);
				dodVw.setText("Died: " + indiv.getDOD());

				ImageView genderImgVw = (ImageView) this.findViewById(R.id.imgIndividualGender);
				TextView genderVw = (TextView) this.findViewById(R.id.txtIndividualGender);
				if (indiv.sex != null && indiv.sex.equalsIgnoreCase("M")) {
					genderVw.setText("Male");
					//					genderVw.setBackgroundDrawable(new BitmapDrawable(BitmapFactory.decodeResource(this.getResources(),
					//							R.drawable.ind_lst_ind_male)));
					genderImgVw.setImageBitmap(BitmapFactory.decodeResource(this.getResources(), R.drawable.gender_male));
				} else if (indiv.sex != null && indiv.sex.equalsIgnoreCase("F")) {
					genderVw.setText("Female");
					//					genderVw.setBackgroundDrawable(new BitmapDrawable(BitmapFactory.decodeResource(this.getResources(),
					//							R.drawable.ind_lst_ind_female)));
					genderImgVw.setImageBitmap(BitmapFactory.decodeResource(this.getResources(), R.drawable.gender_female));
				} else {
					genderVw.setText("Unknown");
				}

				this.updateIndividualDetailsEvents(indiv);
				this.updateIndividualDetailsChildren(indiv);
				//this.updateIndividualDetailsMedia(indiv);
			}
		} catch (Exception e) {
			Log.e(LOG_TAG, e.getMessage());
			//Toast.makeText(this, "Exception Caught populating Person Details", Toast.LENGTH_SHORT).show();
		}
	}

	private void updateIndividualDetailsChildren(IndividualRecord indiv) {

		ListView lstChildren = (ListView) this.findViewById(R.id.layoutIndividualChildrenList);
		List<String> childrenIds = this.individualCntrlr.getChildrenXrefs(indiv);
		if (childrenIds != null) {
			IndividualChildrenListRowAdapter indivEvntAdapter = new IndividualChildrenListRowAdapter(this,
					R.layout.individual_event_list_view_row, childrenIds);

			//FIXME : indivEvntAdapter.sort(comparator);
			lstChildren.setAdapter(indivEvntAdapter);
			indivEvntAdapter.notifyDataSetChanged();

			lstChildren.requestLayout();
		}
	}

	private void updateIndividualDetailsEvents(IndividualRecord indiv) {

		ListView lstEvents = (ListView) this.findViewById(R.id.layoutIndividualEventsList);
		ArrayList<IndividualEventStructure> eventList = new ArrayList<IndividualEventStructure>(indiv.indEvent);

		IndividualEventListRowAdapter indivEvntAdapter = new IndividualEventListRowAdapter(this,
				R.layout.individual_event_list_view_row, eventList);

		//FIXME : indivEvntAdapter.sort(comparator);
		lstEvents.setAdapter(indivEvntAdapter);
		indivEvntAdapter.notifyDataSetChanged();

		lstEvents.requestLayout();
	}

	private void updateIndividualDetailsMedia(IndividualRecord indiv) {

		List<MultimediaLink> mediaList = indiv.multimediaLink;
		ImageView indivPictVw = (ImageView) this.findViewById(R.id.layoutIndividualImgVwPicture);

		//--------------------------
		Bitmap bmp = null;
		if (mediaList != null & mediaList.size() > 0) {
			//set the image from the first multimedia item
			//MultimediaLink mm = mediaList.get(0);
			//			if (mm.fileReference != null && mm.fileReference.length() > 0) {
			//				File tmpf = new File(mm.fileReference);
			//				String newFilename = AGeneDb.getGedomImagePathDir() + tmpf.getName();
			//				try {
			//					bmp = ImageFunctions.getImage(newFilename);
			//					if (bmp == null) {
			//						bmp = ImageFunctions.getImage(AGeneDb.getGedomPathDir() + tmpf.getName());
			//					}
			//				} catch (Throwable e) {
			//					Log.e(LOG_TAG, e.getMessage());
			//				}
			//			}
		} else {
			bmp = BitmapFactory.decodeResource(this.getResources(), R.drawable.unknown_prsn);
		}
		if (bmp == null) {
			bmp = BitmapFactory.decodeResource(this.getResources(), R.drawable.unknown_prsn);
		}
		indivPictVw.setImageDrawable(new BitmapDrawable(ImageFunctions.scaleImage(bmp, 48)));
		//------------------------

		Gallery galleryVw = (Gallery) this.findViewById(R.id.galleryPictures);
		for (int x = 0; x < mediaList.size(); x++) {
			//MultimediaLink mm = mediaList.get(x);
			//ImageView img = new ImageView(this);
			//			try {
			//				if (mm.fileReference != null && mm.fileReference.length() > 0) {
			//					File tmpf = new File(mm.fileReference);
			//					String newFilename = AGeneDb.getGedomImagePathDir() + tmpf.getName();
			//					tmpf = new File(newFilename);
			//					if (tmpf.exists()) {
			//						bmp = new BitmapDrawable(newFilename).getBitmap();
			//					} else {
			//						newFilename = AGeneDb.getGedomPathDir() + tmpf.getName();
			//						tmpf = new File(newFilename);
			//						if (tmpf.exists()) {
			//							bmp = new BitmapDrawable(newFilename).getBitmap();
			//						}
			//					}
			//				}
			//			} catch (Exception e) {
			//				Log.e(LOG_TAG, e.getMessage());
			//				//Toast.makeText(this, "Exception Caught updating individual media", Toast.LENGTH_SHORT).show();
			//			}
		}
		galleryVw.setFadingEdgeLength(40);

	}

}